package cn.ivicar.sms.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

import cn.com.carsmart.ws.model.SmsHistory;
import cn.com.carsmart.ws.model.ValidateCode;
import cn.ivicar.sms.service.util.HttpClientUtil;
import cn.ivicar.sms.service.util.SmsProperties;

public class SmsService {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(SmsService.class);

	private static HttpClient httpclient;
	@Inject
	private SmsHistoryService historyService;

	public boolean sendSms(String mobile, String content) throws ClientProtocolException, IOException {

		boolean result = false;
		httpclient = HttpClientUtil.getHttpClient();
		String url = "http://dx.ipyy.net/sms.aspx";
		String accountName = SmsProperties.getString("sms.account");
		String password = SmsProperties.getString("sms.password");

		HttpPost post = new HttpPost(url);
		post.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("action", "send"));
		nvps.add(new BasicNameValuePair("userid", ""));
		nvps.add(new BasicNameValuePair("account", accountName));
		nvps.add(new BasicNameValuePair("password", password));
		nvps.add(new BasicNameValuePair("mobile", mobile)); // 多个手机号用逗号分隔
		nvps.add(new BasicNameValuePair("content", content));
		nvps.add(new BasicNameValuePair("sendTime", ""));
		nvps.add(new BasicNameValuePair("extno", ""));

		post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

		
		int i = 1;
		while (i <= 3) {

			try {
                HttpResponse response = httpclient.execute(post);
                LOGGER.info(String.format("第 %s次尝试发送短信，mobile:%s,StatusLine:", i, mobile, response.getStatusLine()));

                HttpEntity entity = response.getEntity();
                // 将字符转化为XML
                String returnString = EntityUtils.toString(entity, "UTF-8");
                Document doc = DocumentHelper.parseText(returnString);
                // 获取根节点
                Element rootElt = doc.getRootElement();
                // 获取根节点下的子节点的值
                String returnstatus = rootElt.elementText("returnstatus").trim();
                String message = rootElt.elementText("message").trim();
                String remainpoint = rootElt.elementText("remainpoint").trim();
                String taskID = rootElt.elementText("taskID").trim();
                String successCounts = rootElt.elementText("successCounts").trim();

                LOGGER.info(returnString);
                LOGGER.info("返回状态为：" + returnstatus);
                LOGGER.info("返回信息提示：" + message);
                LOGGER.info("返回余额：" + remainpoint);
                LOGGER.info("返回任务批次：" + taskID);
                LOGGER.info("返回成功条数：" + successCounts);
                EntityUtils.consume(entity);
                if ("Success".equals(returnstatus)) {

                	// TODO:将发送的短信内容存入数据库，以供未来排查
                	SmsHistory history = new SmsHistory();
                	history.setMobile(mobile);
                	history.setAction("send");
                	history.setContent(content);
                	history.setReturnStatus(returnstatus);
                	history.setMessage(message);
                	history.setRemainpoint(remainpoint);
                	history.setTaskId(taskID);
                	history.setSuccesscounts(successCounts);
                	historyService.insert(history);
                	result = true;
                	break;
                }
                
            } catch (Exception e) {
                LOGGER.warn("发送短信出错", e);

            }
			i++;
		}

		
		return result;
	}

	public static void main(String[] args) throws Exception {
		SmsService smsService = new SmsService();
		smsService.sendSms("18510086917", "【全景监控】尊敬的客户，您收到的验证码是：236543，请输入以完成验证，切勿将验证码告知他人。若非本人操作，请忽略此短信。五分钟内有效。");
	}

	public void sendSms(ValidateCode code, String content, Integer timeout) {

		content = content == null ? String.format("【全景监控】尊敬的客户，您收到的验证码是：%s，%s分钟内有效,请输入以完成验证，切勿将验证码告知他人。若非本人操作，请忽略此短信。",
				code.getValidateCode(), timeout == null ? 30 : timeout) : content;
		try {
			sendSms(code.getMobile(), content);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendSms(ValidateCode code) {
		sendSms(code, null, null);
	}

	public void sendSms(ValidateCode code, String content) {
		sendSms(code, content, null);
	}

	public void sendSms(ValidateCode code, Integer timeout) {
		sendSms(code, null, timeout);
	}
}
